﻿namespace Sgr.BillNumbering
{
    /// <summary>
    /// 编码规则选项配置
    /// </summary>
    public class CodeOptions
    {
        /// <summary>
        /// 编码规则集合（私有，仅允许只读访问）
        /// </summary>
        private readonly Dictionary<string, CodeRule> _rules = new();

        /// <summary>
        /// 只读访问编码规则集合
        /// </summary>
        public IReadOnlyCollection<CodeRule> Rules => _rules.Values;

        /// <summary>
        /// 添加编码规则
        /// </summary>
        public CodeOptions AddRule(CodeRule rule)
        {
            ArgumentNullException.ThrowIfNull(rule);

            if (string.IsNullOrWhiteSpace(rule.RuleName))
                throw new ArgumentException("RuleName 不能为空", nameof(rule));

            //if (_rules.ContainsKey(rule.RuleName))
            //    throw new ArgumentException($"名称为 '{rule.RuleName}' 的规则已存在。");

            var key = rule.RuleName.Trim();
            _rules[key] = rule;

            return this;
        }

        /// <summary>
        /// 根据规则名称获取编码规则
        /// </summary>
        public CodeRule? GetRule(string ruleName)
        {
            if (ruleName == null) return null;
            _rules.TryGetValue(ruleName, out var rule);
            return rule;
        }

        /// <summary>
        /// 移除指定规则名称的编码规则
        /// </summary>
        public bool RemoveRule(string ruleName)
        {
            return _rules.Remove(ruleName);
        }

        /// <summary>
        /// 默认段大小（每次从DB预分配多少个号）
        /// </summary>
        public int DefaultSegmentSize { get; set; } = 500;

        /// <summary>
        /// 懒惰清理阈值（超过此数量时概率触发清理）
        /// </summary>
        public int LazyCleanupThreshold { get; set; } = 100_000;

        /// <summary>
        /// 单次清理最多移除的过期段数量（增量限制）
        /// </summary>
        public int CleanupMaxRemovePerRound { get; set; } = 1000;

        /// <summary>
        /// 最小清理间隔（毫秒，节流），小于该间隔时不再重复执行清理
        /// </summary>
        public int CleanupMinIntervalMs { get; set; } = 5000;
    }
}